package com.cats.template.sys.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cats.template.sys.exception.SqlException;
import com.cats.template.sys.mapper.RoleMapper;
import com.cats.template.sys.pojo.model.RoleModel;
import com.cats.template.sys.pojo.model.RolePermissionsModel;
import com.cats.template.sys.services.RolePermissionsService;
import com.cats.template.sys.services.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author duxiaobo
 * @date 2021/9/102:39 下午
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleModel> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionsService rolePermissionsService;

    @Override
    public Set<RoleModel> getRoleListByUserId(Long userId) {
        return roleMapper.getRoleListByUserId(userId);
    }

    @Override
    public Boolean configPermissions(Long roleId, Set<Long> permissionIds) {
        boolean deleteFlag = rolePermissionsService.deleteByRoleId(roleId);
        if (!deleteFlag) {
            throw new SqlException();
        }
        List<RolePermissionsModel> models = permissionIds.stream().map(permissionId -> new RolePermissionsModel().setRoleId(roleId).setPermissionId(permissionId)).collect(Collectors.toList());
        boolean flag = rolePermissionsService.saveOrUpdateBatch(models);
        if (!flag) {
            throw new SqlException();
        }
        return true;
    }
}
